<?php

namespace app\api\controller\shop;

use app\admin\model\usermanage\Users;
use app\api\model\Register;
use app\api\model\shop\Exchange as ExchangeModel;
use app\api\model\shop\ExchangeOrder;
use app\api\model\Address;
use app\common\controller\Api;
use app\common\model\User;
use fast\Security;
use Psr\Log\Test\DummyTest;
use think\Db;
use think\Exception;

/**
 * 积分兑换接口
 */
class Exchange extends Api
{
    protected $noNeedLogin = ['index', 'show'];
    protected $noNeedRight = ['*'];

    /**
     * 积分兑换列表
     */
    public function index()
    {
        $list = ExchangeModel::tableList($this->request->param());
        $this->success('',$list);
    }

    /**
     * 积分兑换详情
     */
    public function show()
    {
        $id = $this->request->param('id/d');
        if (!$id) {
            $this->error('参数错误');
        }
        $row = ExchangeModel::get($id);
        if (empty($row)) {
            $this->error('兑换商品未找到');
        }
        if ($row->stocks <= 0) {
            $this->error('兑换商品库存不足');
        }
        $addressList = [];
        if ($this->auth->isLogin()) {
            $addressList = Address::where('user_id', $this->auth->id)->select();
        }

        $data = [
            'addressList'=>$addressList,
            'info'=>$row
        ];
        $this->success('',$data);
    }

    /**
     * 积分兑换
     */
    public function exchange()
    {

        $address_id = $this->request->post('address_id/d');
        $memo = $this->request->post('memo');
        $nums = (int)$this->request->post('nums/d', 1);
        $exchange_id = $this->request->post('exchange_id/d');
        $pay_pwd = input('pay_pwd','');

        $row = ExchangeModel::get($exchange_id);
        if (empty($row)) {
            $this->error('兑换物品不存在');
        }
        $data = [];

        $address = Address::where('id', $address_id)->find();
        if (empty($address)) {
            $this->error('未找到正确地址');
        }

        if ($address->user_id != $this->auth->id) {
            $this->error('不能越权操作');
        }
        $data = array_merge($data, [
            'receiver' => $address->getAttr('name'),
            'mobile'   => $address->mobile,
            'address'  => $address->detail
        ]);

        if ($nums <= 0) {
            $nums = 1;
        }
        $score = bcmul($nums, $row['score']);

        $user = Users::get(['id' => $this->auth->id]);
        if (empty($user->pay_pwd)){
            $this->error('请先设置支付密码');
        }
        $security_model = new Security();

        if (!$security_model->validatePassword($pay_pwd, $user->pay_pwd)) {
            $this->error('支付密码错误');
        }

        if (!$user) {
            $this->error('网络异常');
        }

        if ($this->auth->integral < $score) {
            $this->error('积分不足，无法兑换');
        }
        // 启动事务
        Db::startTrans();
        try {
            $data = array_merge($data, [
                //'type'        => $row->type,
                'memo'        => $memo,
                'score'       => $score,
                'nums'        => $nums,
                'user_id'     => $this->auth->id,
                'exchange_id' => $exchange_id
            ]);
            $order = ExchangeOrder::createOrder($data);
            $row->setDec('stocks');
            $row->setInc('sales');
            //dump($order);die;
            $user->integral -= $score;
            $register = new Register();

            $register->user_id = $user->id;
            $register->register_time = '..';
            $register->continuation = 0;
            $register->setAttr('type',11);
            $register->integral = '-' . $score;
            $register->order_id = $order;
            $register->save();

            // 提交事务
            $user->save();
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交成功，等待管理员处理！');
    }

    /**
     * 我的积分兑换
     */
    public function myExchange()
    {
        $param = $this->request->param();
        $param['user_id'] = $this->auth->id;
        $this->success('获取成功', ExchangeOrder::tableList($param));
    }

    //积分兑换订单详情
    public function info()
    {
        $id = input('id',0);
        $info = ExchangeOrder::get($id);
        $this->success('获取成功', $info);
    }

    //取消
    public function cancel()
    {
        $id = input('id',0);

        $row = ExchangeOrder::get($id);
        if ($row['status']!='created'){
            $this->error('该状态下不可取消');
        }
        $row->status = 'rejected';
        $row->save();

        User::score($row['score'], $row['user_id'], '积分兑换已取消，积分退还');
        //库存，销量回调
        \app\admin\model\shop\Exchange::where('id', $row['exchange_id'])->setInc('stocks', $row['nums']);
        \app\api\model\shop\Exchange::where('id', $row['exchange_id'])->setDec('sales', $row['nums']);

        $this->success('');

    }

    //确认收货
    public function complete()
    {
        $id = input('id',0);

        $row = ExchangeOrder::get($id);
        if ($row['status']!='delivered'){
            $this->error('该状态下不可确认收货');
        }
        $row->status = 'completed';
        $row->save();

        $this->success('');

    }

}
